package com.itheima.es;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * @Description:
 * @Version: V1.0
 */
public class EsCluster {

    //客户端对象
    private RestHighLevelClient client;
    /**
     * 建立连接
     */
    @Before
    public void init() throws IOException {
        //创建Rest客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        //如果是集群，则设置多个主机，注意端口是http协议的端口
                        new HttpHost("192.168.200.151", 9200, "http")
                        ,new HttpHost("192.168.200.152", 9200, "http")
                        ,new HttpHost("192.168.200.153", 9200, "http")
                )
        );
    }

    /**
     * 创建索引库-测试
     * @throws Exception
     */
    @Test
    public void testCreateIndex() throws Exception{
        // 1 创建CreateIndexRequest对象，并指定索引库名称
        CreateIndexRequest indexRequest = new CreateIndexRequest("user");
        // 2 设置指定settings配置(可以默认)
        indexRequest.settings(Settings.builder()
                .put("index.number_of_shards", 3)   // 分片数量
                .put("index.number_of_replicas", 1) // 副本分片
        );


        // 3 设置mapping
        indexRequest.mapping( "{\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"long\"\n" +
                "      },\n" +
                "      \"name\":{\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"age\":{\n" +
                "        \"type\": \"integer\"\n" +
                "      },\n" +
                "      \"gender\":{\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"note\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"standard\"\n" +
                "      }\n" +
                "    }\n" +
                "  }", XContentType.JSON);

        // 4 发起请求
        CreateIndexResponse response = client.indices().create(indexRequest, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

    /**
     * 关闭客户端连接
     */
    @After
    public void close() throws IOException {
        client.close();
    }
}
